package com.aisino.wxkp.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aisino.jshx.been.RequestXxfpInfo;
import com.aisino.jshx.been.ResponseXxfpInfo;
import com.aisino.jshx.converter.impl.ReqInvoiceConverterImpl;
import com.aisino.wxkp.common.date.DateFormate;
import com.aisino.wxkp.common.entity.DecrySmCAInfo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import com.aisino.wxkp.common.basic.WxkpBaseAction;
import com.aisino.wxkp.common.config.Constants;
import com.aisino.wxkp.common.entity.FpWxFpmx;
import com.aisino.wxkp.common.entity.HhoXXKPInfo;
import com.aisino.wxkp.common.entity.JsAeroInfoReturnException;
import com.aisino.wxkp.common.entity.JsonRespon;
import com.aisino.wxkp.common.enums.RCodeEnums;
import com.aisino.wxkp.common.enums.ReqQyxx;
import com.aisino.wxkp.common.fpkj.dto.B_Data;
import com.aisino.wxkp.common.fpkj.dto.B_DataDescription;
import com.aisino.wxkp.common.fpkj.dto.B_ReturnStateInfo;
import com.aisino.wxkp.common.fpkj.dto.GlobalXMLInfo;
import com.aisino.wxkp.common.fpkj.dto.InterfaceXML;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpcx;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkj;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkjDdxx;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkjFptxx;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkjFpxxNew;
import com.aisino.wxkp.common.fpkj.dto.JshxTblFpkjXmxx;
import com.aisino.wxkp.common.util.AjaxUtil;
import com.aisino.wxkp.common.util.Base64G;
import com.aisino.wxkp.common.util.Gzip;
import com.aisino.wxkp.common.util.HttpReqHelper;
import com.aisino.wxkp.common.util.HxJSONUtils;
import com.aisino.wxkp.common.util.InvParseO2X;
import com.aisino.wxkp.common.util.InvParseX2O;
import com.aisino.wxkp.common.util.StringUtil;
import com.aisino.wxkp.common.util.XmlPar;
import com.aisino.wxkp.service.HhoInvService;
import com.aisino.wxkp.service.WXKPService;
import com.aisino.wxkp.service.impl.HhoInvServiceImpl;
import com.aisino.wxkp.service.impl.WXKPServiceImpl;
import com.aisino.xstream.helper.Base64Helper;
import com.thoughtworks.xstream.XStream;

public class WXInvOpenAction extends WxkpBaseAction {
	private static final long serialVersionUID = 1L;
	WXKPService wxkpInvService = new WXKPServiceImpl();
	HhoInvService hhoInvService = new  HhoInvServiceImpl();
	private static final Logger LOGGER = Logger.getLogger(WXInvOpenAction.class);

	public void WXKP(HttpServletRequest request,HttpServletResponse response) throws JsAeroInfoReturnException, Exception {
		response.setContentType("application/json;charset=utf-8 ");
		JsonRespon result = new JsonRespon();
		Double kphjje = 0.00;  Double xmse =0.00;	
		try {
			String c = request.getParameter("c");				// c 客户类型 固定为1000
			String t = request.getParameter("t");				// t 开具类型 1为蓝票，2为红冲，3为重开
			String fpqqlsh = request.getParameter("id");		// ID 业务流水号   BASE64加密：其中+/分别替换为-_   去除=
			String nsrsbh = request.getParameter("xfsh");			// IC 企业纳税人识别号
			String ik = request.getParameter("ik");				// IK 二维码标识 二维码唯一标识，预留字段，可去除
			String billid = request.getParameter("billid")==null?"":request.getParameter("billid");		
			String ghf_mc = Base64G.decode2(request.getParameter("ghf_mc")== null ? "": request.getParameter("ghf_mc"));		        //抬头名称
			String ghf_nsrsbh = Base64G.decode2(request.getParameter("ghf_nsrsbh")== null ? "": request.getParameter("ghf_nsrsbh")); //税号
			String ghf_sj = "11111111111";
//			String ghf_sj = Base64G.decode2(request.getParameter("ghf_sj")== null ? "11111111111": request.getParameter("ghf_sj"));		//电话号码
			String ghf_dwdz = Base64G.decode2(request.getParameter("ghf_dwdz")== null ? "": request.getParameter("ghf_dwdz"));		//单位地址
			String ghf_khyh = Base64G.decode2(request.getParameter("ghf_khyh")== null ? "": request.getParameter("ghf_khyh"));		//开户银行
			String ghf_yhzh = Base64G.decode2(request.getParameter("ghf_yhzh")== null ? "": request.getParameter("ghf_yhzh"));		//银行账户
			String hjje = request.getParameter("kphjje")==null?"":request.getParameter("kphjje");
//			System.out.println("开票页面数据 客户类型=="+c+"开具类型="+t+"业务流水号="+fpqqlsh+"销方税号="+nsrsbh+"billid="+billid);
//			System.out.println("个人开具数据 购货方名称=="+ghf_mc+"购货方手机="+ghf_sj +"开票合计金额=="+request.getParameter("kphjje"));
//			System.out.println("企业开具数据 购货方名称=="+ghf_mc+"购货方纳税人识别号="+ghf_nsrsbh+"购货方单位地址="+ghf_dwdz+"购货方电话号码="+ghf_sj+"购货方开户银行="+ghf_khyh+"购货方银行账户="+ghf_yhzh);
			
			Map<String, Object> DataMap = wxkpInvService.reqTransData(t,nsrsbh,fpqqlsh,ik,billid);
			JshxTblFpkj xxfpobj = (JshxTblFpkj) DataMap.get("fpkjobj");
			GlobalXMLInfo GloablObj = (GlobalXMLInfo) DataMap.get("globalObj");
			DecrySmCAInfo DecrySmCA= (DecrySmCAInfo) DataMap.get("DecrySmCA");
			//淮安水厂
			if(DecrySmCA.getTaxpayerid().equals("9132080013943150XH")&& DecrySmCA.getCode().equals("0000")){
				 HhoXXKPInfo  reqHHOFpkj = hhoInvService.reqHHOFpkj(xxfpobj, GloablObj);
				 String sjson = hhoInvService.respHHOView(reqHHOFpkj,xxfpobj,c,t,ik);
				 System.out.println(sjson);
				 writeToResponseSize(response,sjson);
			}else{
			List<JshxTblFpkjXmxx> xmmxList = xxfpobj.getXmxxs();
			xxfpobj.getFptt().setFpqqlsh(fpqqlsh);
			xxfpobj.getFptt().setKpxm(xmmxList.get(0).getXmmc());
			xxfpobj.getFptt().setDsptbm(DecrySmCA.getUsername());
			xxfpobj.getFptt().setCzdm("10");
			
			xxfpobj.getFptt().setNsrsbh(DecrySmCA.getTaxpayerid());
			xxfpobj.getFptt().setNsrmc(ReqQyxx.getQymc(String.valueOf(DecrySmCA.getId())));

			xxfpobj.getFptt().setGhfmc(ghf_mc.replaceAll(" ", ""));								//购货方信息
			xxfpobj.getFptt().setGhfSj("11111111111");
			xxfpobj.getFptt().setGhfNsrsbh(ghf_nsrsbh.replaceAll(" ", ""));
			xxfpobj.getFptt().setGhfDz(ghf_dwdz.replaceAll(" ", ""));
			xxfpobj.getFptt().setGhfGddh(ghf_sj.replaceAll(" ", ""));
			xxfpobj.getFptt().setGhfYhzh((ghf_khyh+ghf_yhzh).replaceAll(" ", ""));
			
			if("".equals(xxfpobj.getFptt().getXhfmc()) || xxfpobj.getFptt().getXhfmc()==null){
				xxfpobj.getFptt().setXhfmc(ReqQyxx.getQymc(String.valueOf(DecrySmCA.getId())));		//销货方信息
			}
			if("".equals(xxfpobj.getFptt().getXhfNsrsbh()) || xxfpobj.getFptt().getXhfNsrsbh()==null){
				xxfpobj.getFptt().setXhfNsrsbh(DecrySmCA.getTaxpayerid());
			}
			if("".equals(xxfpobj.getFptt().getXhfDz()) || xxfpobj.getFptt().getXhfDz()==null){
				xxfpobj.getFptt().setXhfDz(ReqQyxx.getQydz(String.valueOf(DecrySmCA.getId()))); 
			}
			if("".equals(xxfpobj.getFptt().getXhfDh()) || xxfpobj.getFptt().getXhfDh()==null){
				xxfpobj.getFptt().setXhfDh(ReqQyxx.getQydh(String.valueOf(DecrySmCA.getId())));
			}
			if("".equals(xxfpobj.getFptt().getXhfYhzh()) || xxfpobj.getFptt().getXhfYhzh()==null){
				xxfpobj.getFptt().setXhfYhzh(ReqQyxx.getQyyhzh(String.valueOf(DecrySmCA.getId())));
			}
			if(ghf_nsrsbh.equals(null) || ghf_nsrsbh==""){	
				System.out.println("03"+ghf_nsrsbh);
				// 购货方企业类型 01:企业 02：机关事业单位 03：个人  04：其它		
				xxfpobj.getFptt().setGhfqylx("03");
			}else{
				System.out.println("01"+ghf_nsrsbh);
				xxfpobj.getFptt().setGhfqylx("01");
			}
			for (int i = 0; i < xmmxList.size(); i++) {
				kphjje+=paseStr2DoubleRound(xmmxList.get(i).getXmje(),2);
				xmse+=paseStr2DoubleRound(xmmxList.get(i).getSe(),2);
			}
			xxfpobj.getFptt().setKphjje(paseStrRound(String.valueOf(kphjje),2));				//开票合计金额
			xxfpobj.getFptt().setHjse(paseStrRound(String.valueOf(xmse),2));					//合计税额
			xxfpobj.getFptt().setHjbhsje(paseStrRound(String.valueOf(kphjje-xmse),2));			//不含税金额

			if (xxfpobj.getDdxx() == null) {
				JshxTblFpkjDdxx ddxx = new JshxTblFpkjDdxx();
				ddxx.setDdh(fpqqlsh);
				ddxx.setDdlx("9999");
				xxfpobj.setDdxx(ddxx);
			}

			if ("2".equals(xxfpobj.getFptt().getKplx())) {										//红票
				String v_bz = xxfpobj.getFptt().getBz();
				if (v_bz == null) {
					v_bz = "";
				}
				xxfpobj.getFptt().setBz(
						"对应正数发票代码:" + xxfpobj.getFptt().getYfpDm() + "号码:"
								+ xxfpobj.getFptt().getYfpHm() + " " + v_bz);
				if (StringUtil.checkStrIsEmpty(xxfpobj.getFptt().getTschbz())) {
					xxfpobj.getFptt().setTschbz("0");											// 0正常冲红(电子发票) 1特殊冲红(冲红纸质等)
				}
			}

			//拼装请求报文
			String innerXml = InvParseO2X.toFpkj(xxfpobj);
			GlobalXMLInfo globalobj = InvParseO2X.assembleGlobalInfo(DecrySmCA.getUsername(), DecrySmCA.getPassword(), DecrySmCA.getAuthorizationcode(),DecrySmCA.getTaxpayerid());
			B_Data dataobj = new B_Data();
			Base64 base64=new Base64();
			dataobj.setDataDescription(new B_DataDescription());
			dataobj.setContent(new String(base64.encode(innerXml.getBytes("UTF-8")),"UTF-8"));
			String kjqqbw = InvParseO2X.assembleGlobalInfoXMl(globalobj, dataobj);
			if(kjqqbw.equals("")){
				throw new JsAeroInfoReturnException("E9000",RCodeEnums.getMsgs("E9000"));
			}
			// ① 调用开具接口地址
			String responeXml = postClServerRequest(kjqqbw,Constants.TransferServicePro_zzs);
//			String responeXml = postClServerRequest(kjqqbw,Constants.TransferServicePro_zlkp);
			Map<String, Object> itxml = InvParseX2O.getInterface(responeXml);
//			System.out.println("开票返回报文\n"+responeXml);
			// 3. 校验数据合法性
			if (responeXml == "") {
				throw new JsAeroInfoReturnException("E9000", RCodeEnums.getMsgs("9000"));
			}

			//解析返回报文
			GlobalXMLInfo globalInfos = (GlobalXMLInfo) itxml.get(XmlPar.GLOBALINFO);
			B_ReturnStateInfo returneStateInfo =(B_ReturnStateInfo)itxml.get(XmlPar.RETURNSTATEINFO);
//			System.out.println("解析返回报文对象 Code=="+returneStateInfo.getReturnCode()+"\tMsg=="+returneStateInfo.getReturnMessage());
			B_Data data = (B_Data) itxml.get(XmlPar.ZZSDATA);
//			String Result = Gzip.gunzip(data.getContent());
//			System.out.println("开票返回内层报文=="+Result);
			
//			if("0000".equals(returneStateInfo.getReturnCode())){
//				//开票成功
//				JshxTblFpkjFpxxNew retFpkjObj = InvParseX2O.getResponseFPKJInfo(Result);
//				String fpdm = retFpkjObj.getFpDm();
//				String fphm = retFpkjObj.getFpHm();
//				String hjbhsje = retFpkjObj.getHjbhsje();
//				String hjse = retFpkjObj.getKphjse();
//				String kphjje2 = String.valueOf(paseStr2DoubleRound(String.valueOf((Double.valueOf(hjse)+Double.valueOf(hjbhsje))),2));
//				String kprq = retFpkjObj.getKprqStr();
//				StringBuffer url = new StringBuffer(Constants.dispatcher);
//				url.append("?c=").append(c);
//				url.append("&t=").append(t);
//				url.append("&id=").append(fpqqlsh);
//				url.append("&ic=").append(nsrsbh);
//				url.append("&ik=").append(ik);
//				result.setCode("0000");
//				result.setMsg("开票成功");
//				System.out.println(url.toString());
//				result.setData(url.toString());
//				Map<String, Object> goodsMap = new HashMap<String, Object>();
//				goodsMap.put("result", result);
//				goodsMap.put("fpdm", fpdm);
//				goodsMap.put("fphm", fphm);
//				goodsMap.put("kphjje", kphjje2);
//				goodsMap.put("kprq", kprq);
//				goodsMap.put("xhfmc", Base64Helper.encode(xxfpobj.getFptt().getXhfmc()));
//				String sjson = HxJSONUtils.getJSONString(goodsMap);
//				System.out.println(sjson);
//				writeToResponseSize(response,sjson);
//			}else{
//				//抛异常 开票失败
//				throw new JsAeroInfoReturnException("E7007", RCodeEnums.getMsgs("7007"));
//			}
				if(returneStateInfo.getReturnCode().equals("0000")){
					System.out.println("终于进来了====");
					request.setAttribute("xxfpobj", xxfpobj);

					//跳转JSP页面=> WXInvInfoAction
					StringBuffer url = new StringBuffer(Constants.dispatcher);
					url.append("?c=").append(c);
					url.append("&t=").append(t);
					url.append("&id=").append(fpqqlsh);
					url.append("&xfsh=").append(nsrsbh);
					url.append("&ik=").append(ik);
					result.setCode("0000");
					result.setMsg("您的开票请求已提交");
//					System.out.println(url.toString());
					result.setData(url.toString());
					Map<String, Object> goodsMap = new HashMap<String, Object>();
					goodsMap.put("result", result);
					goodsMap.put("ghfmc", Base64Helper.encode(xxfpobj.getFptt().getGhfmc()));
//					System.out.println("发送页面数据=="+Base64Helper.encode(xxfpobj.getFptt().getGhfmc())+"xhfmc"+Base64Helper.encode(xxfpobj.getFptt().getXhfmc()));
					goodsMap.put("xhfmc", Base64Helper.encode(xxfpobj.getFptt().getXhfmc()));
					goodsMap.put("kphjje", xxfpobj.getFptt().getKphjje());
					String sjson = HxJSONUtils.getJSONString(goodsMap);
//					System.out.println(sjson);
					writeToResponseSize(response,sjson);
					}else {
					throw new JsAeroInfoReturnException("E7002",RCodeEnums.getMsgs("E7002"));
					}
				} 
		} catch (JsAeroInfoReturnException e) {
			try {
				result.setCode(e.getCode());
				result.setMsg(e.getMessage());
				Map<String, Object> goodsMap = new HashMap<String, Object>();
				goodsMap.put("result", result);
				AjaxUtil.writeMap(goodsMap, response);
			} catch (Exception e1) {
			}
		}
	}

}
